package com.wangsd.web.face.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wangsd.common.enums.CommonStatic;
import com.wangsd.web.face.entity.Advertisement;
import com.wangsd.web.face.entity.AdvertisementStoreRelation;
import com.wangsd.web.face.entity.Device;
import com.wangsd.web.face.entity.Store;
import com.wangsd.web.face.mapper.AdvertisementMapper;
import com.wangsd.web.face.mapper.AdvertisementStoreRelationMapper;
import com.wangsd.web.face.service.AdvertisementService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wangsd.web.face.service.AdvertisementStoreRelationService;
import com.wangsd.web.face.service.DeviceService;
import com.wangsd.web.face.service.StoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.management.Query;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author generator
 * @since 2019-10-15
 */
@Service
public class AdvertisementServiceImpl extends ServiceImpl<AdvertisementMapper, Advertisement> implements AdvertisementService {

    @Resource
    AdvertisementMapper advertisementMapper;
    @Resource
    AdvertisementStoreRelationMapper advertisementStoreRelationMapper;
    @Autowired
    DeviceService deviceService;
    @Autowired
    StoreService storeService;
    @Autowired
    AdvertisementStoreRelationService advertisementStoreRelationService;

    @Override
    public IPage<Advertisement> selectPage(String code, Integer pageNum, Integer pageSize, Advertisement params) {
        Page<Advertisement> page = new Page<>(pageNum, pageSize);
        IPage<Advertisement> advertisementIPage = null;
        if (params.getType() == 0) {
            advertisementIPage = advertisementMapper.selectListXmlOfBusiness(page, params, code);
        } else {
            advertisementIPage = advertisementMapper.selectListXmlOfMerchant(page, params, code);
        }
        return advertisementIPage;
    }

    @Override
    @Transactional
    public void addOrUpdate(Advertisement params) {
        if (params.getId() == null) {
            advertisementMapper.insert(params);

        } else {
            advertisementMapper.updateById(params);
            /*默认状态则需要删除关联表中数据*/
            if (params.getState() == 1) {
                advertisementStoreRelationMapper.delete(new QueryWrapper<AdvertisementStoreRelation>()
                        .eq("advertisement_id", params.getId()));
            }
        }
        /*List<Long> storeIdList = params.getStoreIdList();
        if (storeIdList != null) {
            List<AdvertisementStoreRelation> relations = new ArrayList<>();
            storeIdList.forEach(storeId -> {
                AdvertisementStoreRelation relation = new AdvertisementStoreRelation();
                relation.setAdvertisementId(params.getId());
                relation.setStoreId(storeId);
                relations.add(relation);
            });
            if (relations.size() > 0) {
                advertisementStoreRelationService.saveBatch(relations);
            }
        }*/
    }

    @Override
    public Integer selectRightCount(Advertisement params) {
        QueryWrapper<Advertisement> queryWrapper = new QueryWrapper<>();
        if (params.getBusinessId() != null) {
            queryWrapper.eq("business_id", params.getBusinessId());
            /*查询默认广告，不能超过5个*/
            queryWrapper.eq("state", 1);
        }
        if (params.getMerchantId() != null) {
            queryWrapper.eq("merchant_id", params.getMerchantId());
        }
        Integer count = advertisementMapper.selectCount(queryWrapper);
        return count;
    }

    @Override
    public List<AdvertisementStoreRelation> selectAdvertisementStoreCount(List<Long> storeIds) {
        List<AdvertisementStoreRelation> relations = advertisementStoreRelationMapper.selectStoreCount(storeIds);
        return relations;
    }

    @Override
    public List<Advertisement> selectRightByDeviceNo(String deviceNo) {
        Device device = deviceService.selectByDeviceNo(deviceNo);
        if (device == null) {
            return null;
        }
        Store store = storeService.getById(device.getStoreId());
        if (store == null) {
            return null;
        }

        /*2019-10-30 新增逻辑，广告和门店进行关联，查询门店与广告的关联关系 start*/
        List<AdvertisementStoreRelation> relations = advertisementStoreRelationMapper.selectList(new QueryWrapper<AdvertisementStoreRelation>()
                .eq("store_id", store.getId()));

        if (relations != null) {
            List<Long> advertisementIdList = relations.stream().map(AdvertisementStoreRelation::getAdvertisementId).collect(Collectors.toList());
            if (advertisementIdList == null || advertisementIdList.size() == 0) {
                return null;
            }
            return advertisementMapper.selectList(new QueryWrapper<Advertisement>().in("id", advertisementIdList));
        }
        /*2019-10-30 新增逻辑，广告和门店进行关联，查询门店与广告的关联关系 end*/


        String[] split = store.getCode().split("-");
        Long merchantId = store.getMerchantId();
        List<Advertisement> advertisements = selectListByMerchantIdOrBusinessId(merchantId, null);
        /*判断，若商户下有广告位，则先查询出商户下的广告位，不足则查询服务商下，两则之和小于等于5*/
        if (advertisements != null) {
            if (advertisements.size() == 5) {
                return advertisements;
            } else {
                /*还差几个广告位，需要从服务商下获取*/
                Integer differ = CommonStatic.DISPLAY_ADVERTISEMENT_USE_COUNT - advertisements.size();
                List<Advertisement> result = selectListByMerchantIdOrBusinessId(null, Long.valueOf(split[0]));
                if (result != null && result.size() <= differ) {
                    /*集合合并到一起*/
                    advertisements.addAll(result);
                } else {
                    for (int i = 0; i < differ; i++) {
                        /*差的直接从服务商广告位中获取*/
                        advertisements.add(result.get(i));
                    }
                }
                return advertisements;
            }
        } else { /*若商户下没有广告位，则只需要查询服务商下的广告位*/
            List<Advertisement> result = selectListByMerchantIdOrBusinessId(null, Long.valueOf(split[0]));
            return result;
        }
    }

    @Override
    public List<Advertisement> selectRightPlusByDeviceNo(String deviceNo) {
        Device device = deviceService.selectByDeviceNo(deviceNo);
        if (device == null) {
            return null;
        }
        Store store = storeService.getById(device.getStoreId());
        if (store == null) {
            return null;
        }
        String code = store.getCode();
        List<Advertisement> list = advertisementMapper.selectList(
                new QueryWrapper<Advertisement>()
                        .eq("state", 1).eq("business_id", code.split("-")[0]).orderByDesc("sort"));
        List<AdvertisementStoreRelation> relations = advertisementStoreRelationMapper.selectList(new QueryWrapper<AdvertisementStoreRelation>()
                .eq("store_id", store.getId()));

        if (relations != null && relations.size() > 0) {
            List<Long> advertisementIdList = relations.stream().map(AdvertisementStoreRelation::getAdvertisementId).collect(Collectors.toList());
            if (advertisementIdList == null || advertisementIdList.size() == 0) {
                return null;
            }
            List<Advertisement> advertisements = advertisementMapper.selectList(new QueryWrapper<Advertisement>().in("id", advertisementIdList));
            list.addAll(advertisements);
            return list;
        }
        return list;
    }

    @Override
    public List<Advertisement> selectAdvertisementAll(String code) {
        QueryWrapper<Advertisement> queryWrapper = new QueryWrapper<>();
        if (code != null) {
            String[] split = code.split(",");
            queryWrapper.eq("business_id", split[0]);
        }
        queryWrapper.eq("status", 1);
        queryWrapper.eq("state", 0);
        List<Advertisement> advertisements = advertisementMapper.selectList(queryWrapper);
        return advertisements;
    }

    @Override
    public Integer selectAdvertisementDefault(String code) {
        QueryWrapper<Advertisement> queryWrapper = new QueryWrapper<>();
        if (code != null) {
            String[] split = code.split(",");
            queryWrapper.eq("business_id", split[0]);
        }
        queryWrapper.eq("state", 1);
        Integer integer = advertisementMapper.selectCount(queryWrapper);
        return integer;
    }

    private List<Advertisement> selectListByMerchantIdOrBusinessId(Long merchantId, Long businessId) {
        QueryWrapper<Advertisement> queryWrapper = new QueryWrapper<>();
        if (merchantId != null) {
            queryWrapper.eq("merchant_id", merchantId);
        }
        if (businessId != null) {
            queryWrapper.eq("business_id", businessId);
        }
        queryWrapper.eq("status", 1);
        List<Advertisement> advertisements = advertisementMapper.selectList(queryWrapper);
        return advertisements;
    }
}
